/**
 * 分享界面
 * SharedActivity.java
 * Car273
 * <p/>
 * Created by 方鹏程 on 2014年4月11日
 * Copyright (c) 1998-2014 273.cn. All rights reserved.
 */

package com.styytech.dadabao.module.share;

import android.app.Service;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.LinearLayout;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.styytech.dadabao.R;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

@ContentView(R.layout.activity_share_dialog)
public class SharedDialogActivity extends BaseActivity implements
        PlatformActionListener, Callback {

    private String LOG_TAG = "SharedDialogActivity";


    @ViewInject(R.id.ly_cancel)//总体
            LinearLayout ly_cancel;

    @ViewInject(R.id.ll_share_weibo)//微博
            LinearLayout ll_share_weibo;

    @ViewInject(R.id.ll_share_qZore)//qq空间
            LinearLayout ll_share_qZore;

    @ViewInject(R.id.ll_share_winx)
    LinearLayout ll_share_winx;

    @ViewInject(R.id.ll_share_friends)
    LinearLayout ll_share_friends;


    @ViewInject(R.id.ll_share_qq)
    LinearLayout ll_share_qq;


    @ViewInject(R.id.ll_share_msn)
    LinearLayout ll_share_msn;


    @ViewInject(R.id.ll_share_email)
    LinearLayout ll_share_email;


    /**
     * 分享的标题部分
     */
    private String share_title;
    /**
     * 分享的文字内容部分
     */
    private String share_text = "";
    /**
     * 分享的图片部分
     */
    private String share_image = null;
    /**
     * 分享的网址部分
     */
    private String share_url;
    /**
     * 分享数据的集合体
     */
    private HashMap<String, Object> map;

    CustomLoadingDialog mdlg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ///设置为true点击区域外消失
        setFinishOnTouchOutside(true);
        super.onCreate(savedInstanceState);

//        setContentView(R.layout.activity_share_dialog);

        // 初始化sdk分享资源
        ShareSDK.initSDK(this);
        // 数据初始化
        initData();
    }

    /**
     * 定义一个函数将dp转换为像素
     *
     * @param dp
     * @return
     */
    public int Dp2Px(float dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dp * scale / 2);
    }

    /**
     * @数据初始化
     */
    private void initData() {

        if (getIntent().getStringExtra("title") != null) { // 标题
            share_title = getIntent().getStringExtra("title");
        }
        if (getIntent().getStringExtra("shareUrl") != null) { // 分享链接
            share_url = getIntent().getStringExtra("shareUrl");
        }
        if (getIntent().getStringExtra("newsPic") != null) { // 分享图片链接
            share_image = getIntent().getStringExtra("newsPic");
        }
        if (getIntent().getStringExtra("content") != null) { // 分享的内容
            share_text = getIntent().getStringExtra("content");
        }

//      初始化要属相的内容
//        share_title = "大大宝";
//        share_text = "我正在使用大大宝手机客户端，你也快来下载吧！" + " http://dadabaoapp.dadajt.com/dadabaoApp/apptool/app/appdownview/down/appDown?businessAppType=6";
//        share_image =
//                "https://www.dadabao.net/client/images/logo.png";
//        share_url = "http://dadabaoapp.dadajt.com/dadabaoApp/apptool/app/appdownview/down/appDown?businessAppType=6";

//        Log.i(LOG_TAG, "share_image:" + share_image);
//        Log.i(LOG_TAG, "share_title:" + share_title);
//        Log.i(LOG_TAG, "share_url:" + share_url);
//        Log.i(LOG_TAG, "share_text:" + share_text);

        map = new HashMap<String, Object>();

    }

    /**
     * 分享
     */
    @OnClick({R.id.ly_cancel, R.id.ll_share_weibo, R.id.ll_share_qZore, R.id.ll_share_winx, R.id.ll_share_friends, R.id.ll_share_qq,
            R.id.ll_share_msn, R.id.ll_share_email})
    public void onClick(View v) {
        // 清空之前可能存在的分项数据
        if (map.size() != 0) {
            map.clear();
        }
        switch (v.getId()) {
            case R.id.ly_cancel:
                finish();
                break;
            // 分享到新浪微博
            case R.id.ll_share_weibo:
                setDialog();
                share_SinaWeibo();
                break;
            // 分享到QQ空间
            case R.id.ll_share_qZore:
                setDialog();
                share_Qzone();
                break;
            // 分享到微信好友
            case R.id.ll_share_winx:
                if (!isInstalledWeiXin()) {
                    InfoMessage.showMessage(this, "请先安装微信");
                    break;
                }
                setDialog();
                share_WxFriend();
                break;
            // 分享到微信朋友圈
            case R.id.ll_share_friends:
                if (!isInstalledWeiXin()) {
                    InfoMessage.showMessage(this, "请先安装微信");
                    break;
                }
                setDialog();
                share_CircleFriend();
                break;
            // 分享到qq
            case R.id.ll_share_qq:
                setDialog();
                share_qq_friend();

                break;
            // 分享到短信
            case R.id.ll_share_msn:

                TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
                if (mTelephonyManager.getSimState() != TelephonyManager.SIM_STATE_READY) //SIM卡没有就绪
                {
                    InfoMessage.showMessage(this, "请确认sim卡是否插入或者sim卡暂时不可用！");
                    break;
                }
                CommonUtils.sendMsgContent(this, share_text);
                break;
            // 分享到邮箱
            case R.id.ll_share_email:
                sendMail(share_title, share_text);

                break;

            default:
                break;
        }
    }

    private void setDialog() {
        mdlg = CommonUtils.getCustomLoadingDialog(this, null, "开启分享", true);
        mdlg.show();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mdlg != null) {
                    mdlg.dismiss();
                }
//                CommonUtils.closeDialog(mdlg);
                SharedDialogActivity.this.finish();
            }
        }, 1000 * 3);
    }

    /**
     * 分享到朋友圈
     */
    private void share_CircleFriend() {
        Platform circle = ShareSDK.getPlatform(this, WechatMoments.NAME);
        // if (!circle.isValid()) {
        // InfoMessage.showMessage(this, "分享失败，请先安装微信");
        // return;
        // }
        map.put("AppId", ShareConfig.APPID_CIRCLE_FRIEND);
        map.put("AppSecret", ShareConfig.APPSECRET_CIRCLE_FRIEND);
        map.put("Enable", ShareConfig.ENABLE_CIRCLE_FRIEND);
        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_CIRCLE_FRIEND);

        ShareSDK.setPlatformDevInfo(WechatMoments.NAME, map);
        ShareSDK.initSDK(this, ShareConfig.APPKEY);

        WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setText(share_text);
        // sp.setImageData(getImageView());
        if (share_image != null) {
            sp.setImageUrl(share_image);
        }

        // sp.setImagePath(share_image);
        sp.setUrl(share_url);

        if (circle != null) {
            circle.setPlatformActionListener(this); // 设置分享事件回调
            // 执行图文分享
            circle.share(sp);
        }
    }

    /**
     * 分享到微信好友
     */
    private void share_WxFriend() {
        Platform circle = ShareSDK.getPlatform(this, Wechat.NAME);
        // if (!circle.isValid()) {
        // InfoMessage.showMessage(this, "分享失败，请先安装微信");
        // return;
        // }
        map.put("AppId", ShareConfig.APPID_WXFRIEND);
        map.put("AppSecret", ShareConfig.APPSECRET_CIRCLE_FRIEND);
        map.put("Enable", ShareConfig.ENABLE_WXFRIEND);
        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_WXFRIEND);

        ShareSDK.setPlatformDevInfo(Wechat.NAME, map);
        ShareSDK.initSDK(this, ShareConfig.APPKEY);

        ShareParams sp = new ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setText(share_text);
//         sp.setImageData(getImageView());
        if (share_image != null) {
            sp.setImageUrl(share_image);
        }
        // sp.setImagePath("");
        sp.setUrl(share_url);

        if (circle != null) {
            circle.setPlatformActionListener(this); // 设置分享事件回调
            // 执行图文分享
            circle.share(sp);
        }
    }

    /**
     * 分享到QQ空间
     */
    private void share_Qzone() {

        map.put("AppId", ShareConfig.APPID_QZONE);
        map.put("AppKey", ShareConfig.APPKEY_QZONE);
        map.put("ShareByAppClient", ShareConfig.SHAREBYAPPCLIENT_QZONE);
        map.put("Enable", ShareConfig.ENABLE_QZONE);
        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_QZONE);

        ShareSDK.setPlatformDevInfo(QZone.NAME, map);
        ShareSDK.initSDK(this, ShareConfig.APPKEY);

        QZone.ShareParams sp = new QZone.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setText(share_text);
        sp.setTitleUrl(share_url);
        if (share_image != null) {
            sp.setImageUrl(share_image);
        }
        // sp.setImagePath("");
        sp.setSite("大大宝");

        Platform qzone = ShareSDK.getPlatform(this, QZone.NAME);
        qzone.setPlatformActionListener(this); // 设置分享事件回调
        // 执行图文分享
        qzone.share(sp);

        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mdlg != null) {
                    mdlg.dismiss();
                }
//                CommonUtils.closeDialog(mdlg);
                SharedDialogActivity.this.finish();
            }
        }, 1000 * 1);
    }

    /**
     * 分享到qq好友
     */
    private void share_qq_friend() {

        // if (!circle.isValid()) {
        // InfoMessage.showMessage(this, "分享失败，请先安装微信");
        // return;
        // }
        map.put("AppId", ShareConfig.APPID_QQ);
        map.put("AppKey", ShareConfig.APPKEY_QQ);
        map.put("ShareByAppClient", ShareConfig.SHAREBYAPPCLIENT_QQ);
        map.put("Enable", ShareConfig.ENABLE_QQ);
        map.put("BypassApproval", ShareConfig.BYPASSAPPROVAL_QQ);


        ShareSDK.setPlatformDevInfo(QQ.NAME, map);
        ShareSDK.initSDK(this, ShareConfig.APPKEY);


        QQ.ShareParams sp = new QQ.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性
        sp.setTitle(share_title);
        sp.setTitleUrl(share_url);
        sp.setText(share_text);
        // sp.setImageData(getImageView());
        if (share_image != null) {
            sp.setImageUrl(share_image);
        }
        // sp.setImagePath("");


        Platform circle = ShareSDK.getPlatform(this, QQ.NAME);


        if (circle != null) {
            circle.setPlatformActionListener(this); // 设置分享事件回调
            // 执行图文分享
            circle.share(sp);
        }

    }

    /**
     * 分享到新浪微博
     */
    private void share_SinaWeibo() {
        map.put("AppKey", ShareConfig.APPKEY_SINA_WEIBO);
        map.put("AppSecret", ShareConfig.APPSECRET_SINA_WEIBO);
        map.put("RedirectUrl", ShareConfig.REDIRECTURL_SINA_WEIBO);
        map.put("ShareByAppClient", ShareConfig.SHAREBYAPPCLIENT_SINA_WEIBO);
        map.put("Enable", ShareConfig.ENABLE_SINA_WEIBO);
        ShareSDK.setPlatformDevInfo(SinaWeibo.NAME, map);
        ShareSDK.initSDK(this, ShareConfig.APPKEY);


        SinaWeibo.ShareParams sp = new SinaWeibo.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);// 一定要设置分享属性


        sp.setText(share_text + share_url);
        sp.setImagePath("null");

        Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
        if (weibo != null) {
            weibo.setPlatformActionListener(this); // 设置分享事件回调
            // 执行图文分享
            weibo.share(sp);
        }
    }

    //发邮件
    private void sendMail(String emailTitle, String emailBody) {
        Intent email = new Intent(Intent.ACTION_SEND);
        email.setType("plain/text");

        //设置邮件默认地址
        // email.putExtra(android.content.Intent.EXTRA_EMAIL, emailReciver);
        //设置邮件默认标题
        email.putExtra(Intent.EXTRA_SUBJECT, emailTitle);
        //设置要默认发送的内容
        email.putExtra(Intent.EXTRA_TEXT, emailBody);
        //调用系统的邮件系统
        startActivityForResult(Intent.createChooser(email, "请选择邮件发送软件"), 1001);
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        // 取消分享菜单的统计
        ShareSDK.logDemoEvent(2, null);
        // 释放资源空间
        ShareSDK.stopSDK(this);
        super.onDestroy();
    }

    public void onComplete(Platform plat, int action,
                           HashMap<String, Object> res) {

        Message msg = new Message();
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }

    public void onCancel(Platform palt, int action) {
        Message msg = new Message();
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = palt;
        UIHandler.sendMessage(msg, this);
    }

    public void onError(Platform palt, int action, Throwable t) {
        t.printStackTrace();
        Message msg = new Message();
        msg.arg1 = 2;
        msg.arg2 = action;
        UIHandler.sendMessage(msg, this);
    }

    public boolean handleMessage(Message msg) {
        String text = actionToString(msg.arg2);

        switch (msg.arg1) {
            case 1:
                // 成功
                text = "分享成功";
                InfoMessage.showMessage(this, text);
//			if (isNews) {
//				updateShareTimes();
//			}
//			SharedDialogActivity.this.finish();

                break;
            case 2:
                // 失败
                // text = "分享失败";
                InfoMessage.showMessage(this, "分享失败");
                break;
            case 3:
                // 取消
                text = "分享已取消";
                InfoMessage.showMessage(this, text);
                break;
        }
//        CommonUtils.closeDialog(mdlg);
//        finish();
        return false;
    }

    /**
     * 将action转换为String
     */
    public static String actionToString(int action) {
        switch (action) {
            case Platform.ACTION_AUTHORIZING:
                return "ACTION_AUTHORIZING";
            case Platform.ACTION_GETTING_FRIEND_LIST:
                return "ACTION_GETTING_FRIEND_LIST";
            case Platform.ACTION_FOLLOWING_USER:
                return "ACTION_FOLLOWING_USER";
            case Platform.ACTION_SENDING_DIRECT_MESSAGE:
                return "ACTION_SENDING_DIRECT_MESSAGE";
            case Platform.ACTION_TIMELINE:
                return "ACTION_TIMELINE";
            case Platform.ACTION_USER_INFOR:
                return "ACTION_USER_INFOR";
            case Platform.ACTION_SHARE:
                return "ACTION_SHARE";
            default: {
                return "UNKNOWN";
            }
        }
    }


    /**
     * 获取传递过来的图片
     *
     * @return
     */
    private Bitmap getImageView() {
        Bitmap bitmap = null;
        Intent intent = getIntent();
        if (intent != null) {
            byte[] bis = intent.getByteArrayExtra("bitmap");
            bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
        }
        return bitmap;
    }

    /**
     * 分享次数上传
     */

    private List<Map<String, Object>> getInstalledApps() {
        //desc=com.tencent.mm
        List<PackageInfo> packages = getPackageManager()
                .getInstalledPackages(0);
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>(
                packages.size());
        for (int j = 0; j < packages.size(); j++) {
            Map<String, Object> map = new HashMap<String, Object>();
            PackageInfo packageInfo = packages.get(j);
            // 显示非系统软件
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                map.put("img",
                        packageInfo.applicationInfo.loadIcon(
                                getPackageManager()).getCurrent());
                map.put("name",
                        packageInfo.applicationInfo.loadLabel(
                                getPackageManager()).toString());
                map.put("desc", packageInfo.packageName);
                listMap.add(map);
            }
        }
        return listMap;
    }

    private boolean isInstalledWeiXin() {
        List<Map<String, Object>> haveApp = getInstalledApps();
        for (int i = 0; i < haveApp.size(); i++) {
            boolean isHaveApp = haveApp.get(i).containsValue("com.tencent.mm");
            if (isHaveApp) {
                return true;
            }

        }
        return false;
    }
}
